/**
 * 通用类型基础 -generics base
 * 
 * 
 */

 // 在没有通用类型先，为了实现i32比较i32, char比较char，不得不写两个函数
 // 如果类似的需求有10个，是不是要烦死?

 fn largest_i32(list: &[i32]) -> &i32 {
    let mut largest = &list[0];
    for item in list {
        if item > largest {
            largest = item;
        }
    }
    largest
}

fn largest_char(list: &[char]) -> &char {
    let mut largest = &list[0];
    for item in list {
        if item > largest {
            largest = item;
        }
    }
    largest
}

//使用上通用类型后的取最大值函数，这里只要一个即可
//如果没有对T进行限定，会报告异常: binary operation `>` cannot be applied to type `&T`
//所以必须使用 T: xxxx的方式进行限定
fn largest<T: std::cmp::PartialOrd>(list: &[T]) -> &T {
    let mut largest = &list[0];
    for item in list {
        if item > largest {
            largest = item;
        }
    }
    largest
}

fn main() {
    let number_list = vec![34, 50, 25, 100, 65];
    let char_list = vec!['y', 'm', 'a', 'q'];

    let result = largest_i32(&number_list);
    println!("最大数值 of {:?} is {result}", number_list);
    let result = largest_char(&char_list);
    println!("最大字符 of {:?} is {result}", char_list);

    println!("使用带通用类型参数的函数来计算最大值");
    let result = largest(&number_list);
    println!("最大数值 of {:?} is {result}", number_list);
    let result = largest(&char_list);
    println!("最大字符 of {:?} is {result}", char_list);
}